package com.lzx.iteam;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceTeamAdapter;
import com.lzx.iteam.adapter.WeeklyChooseYearMonthAdapter;
import com.lzx.iteam.adapter.WeeklyMainListAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.ApprovalGroupData;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.bean.WeeklyDataBean;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.WeeklyGroupMsg;
import com.lzx.iteam.net.WeeklyListMsg;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.PinnedSectionListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Megan on 16/5/23.
 */
public class WeeklyMainActivity extends MyBaseActivity implements View.OnClickListener, View.OnTouchListener {


    @FindViewById(id = R.id.ll_weekly_main_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.weekly_main_ll_help)
    private LinearLayout mLayoutHelp;
    @FindViewById(id = R.id.ll_weekly_main_no_data)
    private LinearLayout mLayoutNoData;
    @FindViewById(id = R.id.ll_weekly_main_title)
    private LinearLayout mLayoutTitle;
    @FindViewById(id = R.id.ll_weekly_create)
    private LinearLayout mLayoutCreate;
    @FindViewById(id = R.id.ll_weekly_main_year)
    private LinearLayout mLayoutYear;
    @FindViewById(id = R.id.ll_weekly_main_month)
    private LinearLayout mLayoutMonth;
    @FindViewById(id = R.id.lv_weekly_main_list)
    private PinnedSectionListView mLvList;
    @FindViewById(id = R.id.ll_weekly_main_month_grid)
    private LinearLayout mLlMonth;
    @FindViewById(id = R.id.gv_weekly_main_month_grid)
    private GridView mGvMonth;
    @FindViewById(id = R.id.view_gv_bottom)
    private View mViewCancel;
    @FindViewById(id = R.id.tv_weekly_main_month_clear)
    private TextView mTvMonthClear;
    @FindViewById(id = R.id.lv_weekly_main_year_list)
    private ListView mLvYear;
    @FindViewById(id = R.id.tv_weekly_main_month_text)
    private TextView mTvMonthText;
    @FindViewById(id = R.id.tv_weekly_main_month)
    private TextView mTvMonth;
    @FindViewById(id = R.id.iv_weekly_main_month_arrow)
    private ImageView mIvMonthArrow;
    @FindViewById(id = R.id.tv_weekly_main_year_text)
    private TextView mTvYearText;
    @FindViewById(id = R.id.tv_weekly_main_year)
    private TextView mTvYear;
    @FindViewById(id = R.id.iv_weekly_main_year_arrow)
    private ImageView mIvYearArrow;
    @FindViewById(id = R.id.iv_weekly_main_my)
    private ImageView mIvMyWeekly;
    @FindViewById(id = R.id.iv_weekly_main_manage)
    private ImageView mIvManage;
    @FindViewById(id = R.id.iv_weekly_main_arrow)
    private ImageView mIvArrow;
    @FindViewById(id = R.id.tv_weekly_main_team)
    private TextView mTvTeam;

    private Dialog mTeamDialog;
    private Dialog mProgressDialog;
    private ArrayList<WeeklyDataBean> weeklyDataBeans = new ArrayList<WeeklyDataBean>();
    private ArrayList<Object> mGroupDatas;
    private ApprovalGroupData mGroup;
    private String mGroupId;
    private final int GET_MY_GROUP = 10001;
    private final int GET_WEEKLY_LIST = 10002;

    private int curYear;

    private int yearPostion = 2;
    private int monthPosition = -1;
    private String[] month = {"一月", "七月", "二月", "八月", "三月", "九月", "四月", "十月", "五月", "十一月", "六月", "十二月"};
    private String[] year;
    private String[] s = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
    private boolean isFirst;

    private WeeklyChooseYearMonthAdapter yearAdapter;
    private WeeklyChooseYearMonthAdapter monthAdapter;
    private WeeklyMainListAdapter weeklyListAdapter;

    private CloudDBOperation mCloudDBOperation;
    public static boolean isLoad = false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_MY_GROUP:
                    if (msg.arg1 == 0) {
                        httpReqDlgDismiss();
                        mGroupDatas = (ArrayList<Object>) msg.obj;
                        if (mGroupDatas.size() > 0) {
                            mGroupId = mPreferenceUtil.getString(PreferenceUtil.WEEKLY_GROUP_ID, "");
                            if (!StringUtil.isEmpty(mGroupId)) {
                                for (int i = 0; i < mGroupDatas.size(); i++) {
                                    ApprovalGroupData attendance = (ApprovalGroupData) mGroupDatas.get(i);
                                    if (mGroupId.equals(attendance.getGroup_id())) {
                                        mGroup = attendance;
                                        break;
                                    }
                                }
                            }
                            if (StringUtil.isEmpty(mGroupId) || mGroup == null) {
                                mGroup = (ApprovalGroupData) mGroupDatas.get(0);
                                mGroupId = mGroup.getGroup_id();
                            }
                            mIvArrow.setVisibility(View.VISIBLE);
                            mTvTeam.setText(mGroup.getGroup_name());
                            if (mGroup.getTodo_count() != 0) {
                                mIvMyWeekly.setImageDrawable(getResources().getDrawable(R.drawable.my_weekly_icon1));
                            } else {
                                mIvMyWeekly.setImageDrawable(getResources().getDrawable(R.drawable.my_weekly_icon));
                            }
                            getFilterWeekly();
                            if (isFirst||isLoad) {
                                getWeeklyList();
                                isFirst = false;
                            }
                        } else {
                            mIvArrow.setVisibility(View.GONE);
                        }
                        // initFragment();

                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case GET_WEEKLY_LIST:
                    if (msg.arg1 == 0) {
                        getFilterWeekly();
                        isLoad = false;
                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }

                    break;
            }

        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.weekly_main_layout);
        Calendar c = Calendar.getInstance();
        curYear = c.get(Calendar.YEAR);
        year = new String[3];
        year[0] = curYear + "年";
        year[1] = curYear - 1 + "年";
        year[2] = "不限";

        yearAdapter = new WeeklyChooseYearMonthAdapter(this, 0);
        yearAdapter.bindData(year);
        mLvYear.setAdapter(yearAdapter);

        monthAdapter = new WeeklyChooseYearMonthAdapter(this, 1);
        monthAdapter.bindData(month);
        mGvMonth.setAdapter(monthAdapter);

        mCloudDBOperation = new CloudDBOperation(this);
        isFirst = true;
        httpReqDlgShow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getMyGroups();
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mLayoutCreate.setOnClickListener(this);
        mLayoutTitle.setOnClickListener(this);
        mTvMonthClear.setOnClickListener(this);
        mLayoutYear.setOnClickListener(this);
        mLayoutMonth.setOnClickListener(this);
        mIvManage.setOnClickListener(this);
        mIvMyWeekly.setOnClickListener(this);
        mLayoutHelp.setOnClickListener(this);

        mLvYear.setOnTouchListener(this);
        mViewCancel.setOnClickListener(this);

        mLvYear.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                yearPostion = position;
                yearAdapter.setChooseYear(yearPostion);
                mLvYear.setVisibility(View.GONE);
                mTvYear.setText(year[position]);
                mTvYearText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvYear.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvYearArrow.setImageResource(R.drawable.arrow_down1);
                getFilterWeekly();
            }
        });

        mGvMonth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                monthPosition = position;
                monthAdapter.setChooseMonth(monthPosition);
                mLlMonth.setVisibility(View.GONE);
                mTvMonth.setText(month[position]);
                mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                getFilterWeekly();
            }
        });

        mLvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!StringUtil.isEmpty(weeklyDataBeans.get(i).getWeeklyIds())) {
                    Intent detail = new Intent(WeeklyMainActivity.this, WeeklyDetailListActivity.class);
                    detail.setAction("weekly_list");
                    detail.putExtra("groupId", mGroupId);
                    detail.putExtra("year",weeklyDataBeans.get(i).getWeeklyYear());
                    detail.putExtra("month",weeklyDataBeans.get(i).getWeeklyMonth());
                    detail.putExtra("weekCount",weeklyDataBeans.get(i).getWeekCount());
                    if (weeklyDataBeans.get(i).getWeeklyMonth() != null) {
                        detail.putExtra("title", s[Integer.parseInt(weeklyDataBeans.get(i).getWeeklyMonth())] + "月第" + s[Integer.parseInt(weeklyDataBeans.get(i).getWeekCount())] + "周");
                    }
                    detail.putExtra("weeklyIds", weeklyDataBeans.get(i).getWeeklyIds());
                    startActivity(detail);
                }

            }
        });
    }

    @Override
    public void initData() {
        weeklyListAdapter = new WeeklyMainListAdapter(this);
        mLvList.setAdapter(weeklyListAdapter);


    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.ll_weekly_main_back:
                finish();
                break;
            case R.id.iv_weekly_main_manage:
                if (mGroupDatas.size() > 0){
                    Intent manager = new Intent(this, ScheduleManagerActivity.class);
                    manager.setAction("weekly_manager");
//                    manager.putExtra("groupId", mGroupId);
                    CloudGroup group = new CloudGroup();
                    group.groupId = Long.parseLong(mGroup.getGroup_id());
                    group.groupName = mGroup.getGroup_name();
                    group.contactId = mGroup.getContact_id();
                    manager.putExtra("group_data",group);
                    startActivity(manager);
                }else{
                    showShortToast("未设置考勤点，请联系管理员");
                }
                break;
            case R.id.iv_weekly_main_my:
                if (mGroupDatas.size() > 0){
                    Intent detail = new Intent(this, WeeklyDetailListActivity.class);
                    detail.setAction("my_weekly");
                    if (mGroup != null) {
                        detail.putExtra("unreadCount", mGroup.getTodo_count());
                    }
                    detail.putExtra("groupId", mGroupId);
                    startActivity(detail);
                }else{
                    showShortToast("未设置考勤点，请联系管理员");
                }
                break;
            case R.id.ll_weekly_create:
                if (mGroupDatas.size() > 0) {
                    Intent intent = new Intent(this, WeeklyCreateActivity.class);
                    intent.putExtra("groupId", mGroupId);
                    startActivity(intent);
                }else{
                    showShortToast("未设置考勤点，请联系管理员");
                }
                break;
            case R.id.ll_weekly_main_title:
                showTeamDialog();
                break;
            case R.id.tv_weekly_main_month_clear:
                monthPosition = -1;
                monthAdapter.setChooseMonth(monthPosition);
                mLlMonth.setVisibility(View.GONE);
                mTvMonth.setText("不限");
                mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                getFilterWeekly();

                break;
            case R.id.ll_weekly_main_year:
                if (mLvYear.getVisibility() == View.VISIBLE) {
                    mLvYear.setVisibility(View.GONE);
                    mTvYearText.setTextColor(getResources().getColor(R.color.schedule_content));
                    mTvYear.setTextColor(getResources().getColor(R.color.schedule_content));
                    mIvYearArrow.setImageResource(R.drawable.arrow_down1);
                } else {
                    mLvYear.setVisibility(View.VISIBLE);
                    mTvYearText.setTextColor(getResources().getColor(R.color.event_btn_click));
                    mTvYear.setTextColor(getResources().getColor(R.color.event_btn_click));
                    mIvYearArrow.setImageResource(R.drawable.arrow_up1);
                }
                mLlMonth.setVisibility(View.GONE);
                mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                break;
            case R.id.ll_weekly_main_month:
                if (mLlMonth.getVisibility() == View.VISIBLE) {
                    mLlMonth.setVisibility(View.GONE);
                    mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                    mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                    mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                } else {
                    mLlMonth.setVisibility(View.VISIBLE);
                    mTvMonthText.setTextColor(getResources().getColor(R.color.event_btn_click));
                    mTvMonth.setTextColor(getResources().getColor(R.color.event_btn_click));
                    mIvMonthArrow.setImageResource(R.drawable.arrow_up1);
                }
                mLvYear.setVisibility(View.GONE);
                mTvYearText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvYear.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvYearArrow.setImageResource(R.drawable.arrow_down1);
                break;
            case R.id.view_gv_bottom:
                mLlMonth.setVisibility(View.GONE);
                mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                break;
            case R.id.weekly_main_ll_help:
                Intent help = new Intent(WeeklyMainActivity.this, WebViewActivity.class);
                help.putExtra("title", "如何发布周报?");
                help.putExtra("type", 18);
                startActivity(help);
                break;
        }
    }

    /**
     * 弹出中间团队选择
     */
    private void showTeamDialog() {

        mTeamDialog = new AlertDialog.Builder(this)
                .create();
        mTeamDialog.show();
        Window window = mTeamDialog.getWindow();
        WindowManager.LayoutParams lp = mTeamDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f;   // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.attendance_team_pop_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        ListView listView = (ListView) window.findViewById(R.id.lv_attendance_team_list);
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);


        AttendanceTeamAdapter adapter = new AttendanceTeamAdapter(this);
        adapter.bindData(mGroupDatas, 2);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mGroup = (ApprovalGroupData) mGroupDatas.get(i);
                mGroupId = mGroup.getGroup_id();
                PreferenceUtil.getInstance(WeeklyMainActivity.this).save(PreferenceUtil.WEEKLY_GROUP_ID, mGroupId);
                mTvTeam.setText(mGroup.getGroup_name());
                if (mGroup.getTodo_count() != 0) {
                    mIvMyWeekly.setImageDrawable(getResources().getDrawable(R.drawable.my_weekly_icon1));
                } else {
                    mIvMyWeekly.setImageDrawable(getResources().getDrawable(R.drawable.my_weekly_icon));
                }

                yearPostion = 2;
                yearAdapter.setChooseYear(yearPostion);
                mLvYear.setVisibility(View.GONE);
                mTvYear.setText(year[yearPostion]);
                mTvYearText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvYear.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvYearArrow.setImageResource(R.drawable.arrow_down1);

                monthPosition = -1;
                monthAdapter.setChooseMonth(monthPosition);
                mLlMonth.setVisibility(View.GONE);
                mTvMonth.setText("不限");
                mTvMonthText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvMonth.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvMonthArrow.setImageResource(R.drawable.arrow_down1);
                getFilterWeekly();
                getWeeklyList();
                mTeamDialog.dismiss();
            }
        });

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTeamDialog.dismiss();
            }
        });
        mTeamDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //   mIvArrow.setImageResource(R.drawable.arrow_down);
            }
        });

    }

    /**
     * 我的团队
     */
    private void getMyGroups() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        WeeklyGroupMsg weeklyGroupMsg = new WeeklyGroupMsg(mHandler.obtainMessage(GET_MY_GROUP), this);
        weeklyGroupMsg.mApi = AsynHttpClient.API_EVENT_WEEKLY_MY_GROUPS;
        weeklyGroupMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(weeklyGroupMsg);
    }

    /**
     * 周报列表
     */
    private void getWeeklyList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        WeeklyListMsg weeklyListMsg = new WeeklyListMsg(mHandler.obtainMessage(GET_WEEKLY_LIST), this, mGroupId);
        weeklyListMsg.mApi = AsynHttpClient.API_EVENT_WEEKLY_LIST;
        weeklyListMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(weeklyListMsg);

    }


    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId()) {
            case R.id.lv_weekly_main_year_list:
                mLvYear.setVisibility(View.GONE);
                mTvYearText.setTextColor(getResources().getColor(R.color.schedule_content));
                mTvYear.setTextColor(getResources().getColor(R.color.schedule_content));
                mIvYearArrow.setImageResource(R.drawable.arrow_down1);
                break;
        }
        return false;
    }

    private void getFilterWeekly() {
        int type = 0;
        if (yearPostion != 0 && yearPostion != 1 && monthPosition == -1) {
            type = 0;
        } else if ((yearPostion == 0 || yearPostion == 1) && monthPosition == -1) {
            type = 1;
        } else if (yearPostion != 0 && yearPostion != 1 && monthPosition != -1) {
            type = 2;
        } else if ((yearPostion == 0 || yearPostion == 1) && monthPosition != -1) {
            type = 3;
        }

        // 0: 不限定年月条件   1：限定年份，不限定月份  2：限定月份，不限定年份  3：限定年份和月份
        ArrayList<WeeklyDataBean> dataBeans;
        if (monthPosition % 2 == 0) {
            dataBeans = mCloudDBOperation.findWeeklyListData(type, year[yearPostion].replace("年", ""), monthPosition / 2 + 1 + "", mGroupId);
        } else {
            dataBeans = mCloudDBOperation.findWeeklyListData(type, year[yearPostion].replace("年", ""), (monthPosition - 1) / 2 + 1 + 6 + "", mGroupId);
        }
        weeklyDataBeans.clear();
        int year = 0;
        for (WeeklyDataBean weeklyDataBean : dataBeans) {
            int tempYear = Integer.parseInt(weeklyDataBean.getWeeklyYear());
            if (tempYear == year) {
                weeklyDataBeans.add(weeklyDataBean);
            } else {
                WeeklyDataBean dataBean = new WeeklyDataBean();
                dataBean.setWeeklyYear(weeklyDataBean.getWeeklyYear());
                weeklyDataBeans.add(dataBean);
                weeklyDataBeans.add(weeklyDataBean);
                year = tempYear;
            }
        }
        if(weeklyDataBeans.size()>0){
            mLvList.setVisibility(View.VISIBLE);
            mLayoutNoData.setVisibility(View.GONE);
            weeklyListAdapter.bindData(weeklyDataBeans);
        }else{
            mLvList.setVisibility(View.GONE);
            mLayoutNoData.setVisibility(View.VISIBLE);
        }
    }

    private void httpReqDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).waitDialog();
//            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

    }

    private void httpReqDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


}